package com.imooc.chart.util;

import java.io.*;

public class FileSplitter {

    public static void splitFile(String originalFileName, int charactersPerFile) {
        try (BufferedReader reader = new BufferedReader(new FileReader(originalFileName))) {
            int fileNumber = 1;
            int characterCount = 0;
            String line;
            BufferedWriter writer = null;

            while ((line = reader.readLine()) != null) {
                if (characterCount == 0 || characterCount + line.length() > charactersPerFile) {
                    if (writer != null) {
                        writer.close();
                    }
                    String newFileName = originalFileName.replace(".txt", fileNumber + ".txt");
                    writer = new BufferedWriter(new FileWriter(newFileName));
                    fileNumber++;
                    characterCount = 0;
                }
                writer.write(line);
                writer.newLine();
                characterCount += line.length();
            }

            if (writer != null) {
                writer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        splitFile("input.txt", 2500);
    }
}